package valentini.android.strike;

import java.util.ArrayList;
import java.util.HashMap;


import valentini.android.strike.R;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;

@SuppressLint("NewApi")
public class TodayStrike extends ListActivity implements
		ActionBar.OnNavigationListener, AnimationListener {

	// action bar
	private ActionBar actionBar;
	Intent intent;

	// Refresh menu item
	public MenuItem refreshMenuItem;

	HtmlParser hp = null;
	ArrayList<HashMap<String, String>> menuItems = null;

	/**
	 * On selecting action bar icons
	 * */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Take appropriate action for each action item click
		switch (item.getItemId()) {
		case R.id.action_preferences:
			intent = new Intent(this, ConfigActivity.class);
			startActivity(intent);
			return true;
		case R.id.action_share:
			return true;
		case R.id.action_contact:
			// check for updates action
			contactMe();
			return true;
		case R.id.action_info:
			intent = new Intent(getApplicationContext(),
					InfoActivity.class);
			startActivity(intent);
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		if (Integer.valueOf(android.os.Build.VERSION.SDK)>10){
			actionBar = getActionBar();
		}
		
		//Intent pushIntent = new Intent(this, BackgroundService.class);  
		//startService(pushIntent);

		// Hide the action bar title
		// actionBar.setDisplayShowTitleEnabled(false);

		if (isNetworkAvailable()) {
			populateList();
		} else {
			showNoConnetionAlert();
		}

	}

	public boolean isNetworkAvailable() {
		ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo activeNetworkInfo = connectivityManager
				.getActiveNetworkInfo();
		return activeNetworkInfo != null && activeNetworkInfo.isConnected();
	}

	@Override
	public boolean onNavigationItemSelected(int arg0, long arg1) {
		// TODO Auto-generated method stub
		return false;
	}

	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.activity_main_actions, menu);
		return super.onCreateOptionsMenu(menu);
	}

	private void populateList() {

		hp = HtmlParser.getInstance();
		
		//hp = new HtmlParser(Constants.url_str);
		//menuItems = hp.getElement(Constants.elementName);
		menuItems = hp.getTodaystrikes();
		// Adding menuItems to ListView
		ListAdapter adapter = new SimpleAdapter(this, menuItems,
				R.layout.list_item, new String[] { Constants.KEY_DATA,
						Constants.KEY_CATEGORIA, Constants.KEY_MODALITA,
						Constants.KEY_SETTORE },
				new int[] { R.id.dataList, R.id.categoriaList,
						R.id.modalitaList, R.id.settoreList });

		setListAdapter(adapter);

		ListView lv = getListView();
		lv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {

				/*
				 * // load the animation
				 * 
				 * Animation animFadein = AnimationUtils.loadAnimation(
				 * getApplicationContext(), R.anim.slide_up);
				 * 
				 * // set animation listener //
				 * animFadein.setAnimationListener();
				 * 
				 * view.startAnimation(animFadein);
				 */
				String data = ((TextView) view.findViewById(R.id.dataList))
						.getText().toString();
				String modalita = ((TextView) view
						.findViewById(R.id.modalitaList)).getText().toString();
				String categoria = ((TextView) view
						.findViewById(R.id.categoriaList)).getText().toString();
				String settore = ((TextView) view
						.findViewById(R.id.settoreList)).getText().toString();

				// Starting new intent
				Intent in = new Intent(getApplicationContext(),
						DettaglioSciopero.class);
				in.putExtra(Constants.KEY_DATA, data);
				in.putExtra(Constants.KEY_CATEGORIA, categoria);
				in.putExtra(Constants.KEY_MODALITA, modalita);
				in.putExtra(Constants.KEY_SETTORE, settore);
				startActivity(in);

			}
		});

	}

	private void showNoConnetionAlert() {

		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(R.string.alert_title)
				.setMessage(R.string.alert_message)
				.setCancelable(false)
				.setNegativeButton(R.string.alert_button,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								// dialog.cancel();
								if (isNetworkAvailable()) {
									populateList();
								} else {
									showNoConnetionAlert();
								}
							}
						});
		AlertDialog alert = builder.create();
		alert.show();
	}

	@Override
	public void onAnimationEnd(Animation arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onAnimationRepeat(Animation arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onAnimationStart(Animation arg0) {
		// TODO Auto-generated method stub

	}

	public void contactMe() {

		Intent i = new Intent(Intent.ACTION_SEND);
		i.setType("message/rfc822");
		i.putExtra(Intent.EXTRA_EMAIL,
				new String[] { "davidev.valentini@gmail.com" });
		i.putExtra(Intent.EXTRA_SUBJECT, R.string.contact_subject);
		i.putExtra(Intent.EXTRA_TEXT, R.string.contact_object);
		try {
			startActivity(Intent.createChooser(i, "Send mail..."));
		} catch (android.content.ActivityNotFoundException ex) {
			Toast.makeText(this, R.string.contact_err,
					Toast.LENGTH_SHORT).show();
		}

	}

}
